﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;

namespace Vision.Core.ActivityComponents.YQL
{
    /// <summary>
    /// 
    /// </summary>
    public class YqlQuery : NativeActivity
    {
        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<string> Query { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<string> ConsumerKey { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        public InArgument<string> ConsumerSecret { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Output")]
        public OutArgument<XmlDocument> XmlDocument { get; set; }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            string url = string.Empty;
            
            if (this.ConsumerKey.Get(context) != null && this.ConsumerSecret.Get(context) != null){
                url = "http://query.yahooapis.com/v1/yql?format=xml&diagnostics=false&q=" + Uri.EscapeUriString(this.Query.Get(context));
                url = OAuth.GetUrl(url, this.ConsumerKey.Get(context), this.ConsumerSecret.Get(context));                
            }
            else {
                url = "http://query.yahooapis.com/v1/public/yql?format=xml&diagnostics=false&q=" + Uri.EscapeUriString(this.Query.Get(context));
                url += "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";                
            }
            
            XmlDocument xmlDoc = new XmlDocument();
            using (WebClient webClient = new WebClient()){
                using (Stream request = webClient.OpenRead(url)){
                    xmlDoc.Load(request);
                }
            }

            this.XmlDocument.Set(context, xmlDoc);
        }
    }
}
